<template>
  <div class="transaction-records">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>交易记录</h2>
      <el-button type="primary" @click="showAddDialog">
        添加交易记录
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <SearchCard
      :default-values="{
        search: '',
        paymentMethod: '',
        payerId: '',
        payeeId: '',
      }"
      @search="handleSearch"
      @reset="handleReset"
    >
      <template #default="{ searchForm }">
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="流水号/交易金额"
            clearable
            @keyup.enter="handleSearch"
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="付款方">
          <el-select
            v-model="searchForm.payerId"
            placeholder="全部付款方"
            clearable
            filterable
            style="width: 150px"
          >
            <el-option
              v-for="entity in allEntities"
              :key="entity.id"
              :label="entity.name"
              :value="entity.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收款方">
          <el-select
            v-model="searchForm.payeeId"
            placeholder="全部收款方"
            clearable
            filterable
            style="width: 150px"
          >
            <el-option
              v-for="entity in allEntities"
              :key="entity.id"
              :label="entity.name"
              :value="entity.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="交易方式">
          <el-select
            v-model="searchForm.paymentMethod"
            placeholder="全部方式"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="(label, key) in PAYMENT_METHODS"
              :key="key"
              :label="label"
              :value="key"
            />
          </el-select>
        </el-form-item>
      </template>
    </SearchCard>

    <!-- 交易记录列表 -->
    <DataTable
      title="交易记录"
      :data="transactions"
      :loading="loading"
      :total="pagination.total"
      :current-page="pagination.page"
      :page-size="pagination.limit"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <el-table-column label="序号" width="60" align="center" fixed="left">
        <template #default="{ $index }">
          {{ (pagination.page - 1) * pagination.limit + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="payerName" label="付款方" min-width="120" />
      <el-table-column prop="payeeName" label="收款方" min-width="120" />
      <el-table-column label="交易时间" min-width="150">
        <template #default="{ row }">
          {{ formatDate(row.transactionTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="amount"
        label="交易金额"
        width="120"
        align="center"
      >
        <template #default="{ row }">
          <span class="amount-text">{{ row.amount }} 元</span>
        </template>
      </el-table-column>
      <el-table-column prop="paymentMethod" label="交易方式" width="100">
        <template #default="{ row }">
          {{ getPaymentMethodLabel(row.paymentMethod) }}
        </template>
      </el-table-column>
      <el-table-column label="确认时间" min-width="150">
        <template #default="{ row }">
          {{ row.confirmTime ? formatDate(row.confirmTime) : "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="serialNumber" label="流水号" min-width="150" />
      <el-table-column label="关联记录" min-width="200">
        <template #default="{ row }">
          <div v-if="row.relatedRecords && row.relatedRecords.length > 0">
            <el-tag
              v-for="(record, index) in row.relatedRecords"
              :key="index"
              size="small"
              class="related-tag"
            >
              {{ record }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="{ row }">
          <OperationButtons>
            <el-button type="primary" size="small" @click="showEditDialog(row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="showDetailDialog(row)">
              详情
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </OperationButtons>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 添加/编辑交易记录对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="transactionFormRef"
        :model="transactionForm"
        :rules="transactionRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款方" prop="payerId">
              <el-select
                v-model="transactionForm.payerId"
                placeholder="请选择付款方"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="entity in allEntities"
                  :key="entity.id"
                  :label="entity.name"
                  :value="entity.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款方" prop="payeeId">
              <el-select
                v-model="transactionForm.payeeId"
                placeholder="请选择收款方"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="entity in allEntities"
                  :key="entity.id"
                  :label="entity.name"
                  :value="entity.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交易时间" prop="transactionTime">
              <el-date-picker
                v-model="transactionForm.transactionTime"
                type="datetime"
                placeholder="请选择交易时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易金额" prop="amount">
              <el-input-number
                v-model="transactionForm.amount"
                :min="0"
                :precision="2"
                placeholder="请输入交易金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交易方式" prop="paymentMethod">
              <el-select
                v-model="transactionForm.paymentMethod"
                placeholder="请选择交易方式"
                style="width: 100%"
              >
                <el-option
                  v-for="(label, key) in PAYMENT_METHODS"
                  :key="key"
                  :label="label"
                  :value="key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认时间">
              <el-date-picker
                v-model="transactionForm.confirmTime"
                type="datetime"
                placeholder="请选择确认时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="流水号" prop="serialNumber">
          <el-input
            v-model="transactionForm.serialNumber"
            placeholder="请输入流水号"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="关联记录">
          <el-select
            v-model="transactionForm.relatedRecords"
            multiple
            placeholder="请选择关联的面单充值记录"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="record in availableRechargeRecords"
              :key="record.id"
              :label="record.label"
              :value="record.label"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 交易记录详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="交易记录详情" width="700px">
      <el-descriptions :column="2" border v-if="currentTransaction">
        <el-descriptions-item label="付款方">{{
          currentTransaction.payerName
        }}</el-descriptions-item>
        <el-descriptions-item label="收款方">{{
          currentTransaction.payeeName
        }}</el-descriptions-item>
        <el-descriptions-item label="交易时间">{{
          formatDate(currentTransaction.transactionTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="交易金额"
          >{{ currentTransaction.amount }} 元</el-descriptions-item
        >
        <el-descriptions-item label="交易方式">{{
          getPaymentMethodLabel(currentTransaction.paymentMethod)
        }}</el-descriptions-item>
        <el-descriptions-item label="确认时间">{{
          currentTransaction.confirmTime
            ? formatDate(currentTransaction.confirmTime)
            : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="流水号" :span="2">{{
          currentTransaction.serialNumber
        }}</el-descriptions-item>
        <el-descriptions-item label="关联记录" :span="2">
          <div
            v-if="
              currentTransaction.relatedRecords &&
              currentTransaction.relatedRecords.length > 0
            "
          >
            <el-tag
              v-for="(record, index) in currentTransaction.relatedRecords"
              :key="index"
              class="related-tag"
            >
              {{ record }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(currentTransaction.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import api from "@/utils/api";
import DataTable from "@/components/DataTable.vue";
import SearchCard from "@/components/SearchCard.vue";
import OperationButtons from "@/components/OperationButtons.vue";
import { PAYMENT_METHODS } from "@/utils/constants";
import { getPaymentMethodLabel, formatDate } from "@/utils/helpers";

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const transactions = ref([]);
const allEntities = ref([]); // 客户和网点的合集
const availableRechargeRecords = ref([]); // 可关联的面单充值记录
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);
const currentTransaction = ref(null);
const transactionFormRef = ref();

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 交易表单
const transactionForm = reactive({
  payerId: "",
  payeeId: "",
  transactionTime: "",
  amount: 0,
  paymentMethod: "",
  confirmTime: "",
  serialNumber: "",
  relatedRecords: [],
});

// 表单验证规则
const transactionRules = {
  payerId: [{ required: true, message: "请选择付款方", trigger: "change" }],
  payeeId: [{ required: true, message: "请选择收款方", trigger: "change" }],
  transactionTime: [
    { required: true, message: "请选择交易时间", trigger: "change" },
  ],
  amount: [
    { required: true, message: "请输入交易金额", trigger: "blur" },
    { type: "number", min: 0, message: "交易金额不能小于0", trigger: "blur" },
  ],
  paymentMethod: [
    { required: true, message: "请选择交易方式", trigger: "change" },
  ],
  serialNumber: [
    { required: true, message: "请输入流水号", trigger: "blur" },
    {
      min: 1,
      max: 100,
      message: "流水号长度在 1 到 100 个字符",
      trigger: "blur",
    },
  ],
};

// 计算属性
const dialogTitle = computed(() =>
  isEdit.value ? "编辑交易记录" : "添加交易记录"
);

// 获取所有实体（客户和网点）
const fetchAllEntities = async () => {
  try {
    const [customersRes, networksRes] = await Promise.all([
      api.get("/customers", { params: { limit: 1000 } }),
      api.get("/networks", { params: { limit: 1000 } }),
    ]);

    const customers = customersRes.data.customers.map((c) => ({
      id: `customer_${c._id}`,
      name: `${c.name}${c.alias ? `(${c.alias})` : ""}`,
      type: "customer",
    }));

    const networks = networksRes.data.networks.map((n) => ({
      id: `network_${n._id}`,
      name: `${n.networkName}(${n.networkCode})`,
      type: "network",
    }));

    allEntities.value = [...customers, ...networks];
  } catch (error) {
    ElMessage.error("获取实体列表失败");
  }
};

// 获取可关联的面单充值记录
const fetchAvailableRechargeRecords = async () => {
  try {
    const response = await api.get("/waybill-recharge/unpaid-records");
    availableRechargeRecords.value = response.data.records.map((record) => ({
      id: record._id,
      label: `${record.shopName.substring(0, 3)}-${formatDateToYYYYMMDD(
        record.transactionTime
      )}-${getPlatformLabel(record.platform)}-${getExpressLabel(
        record.expressCompany
      )}`,
    }));
  } catch (error) {
    ElMessage.error("获取面单充值记录失败");
  }
};

// 格式化日期为YYYYMMDD
const formatDateToYYYYMMDD = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}${month}${day}`;
};

// 获取平台标签
const getPlatformLabel = (platform) => {
  const labels = {
    taobao: "淘宝",
    pinduoduo: "拼多多",
    douyin: "抖音",
    xiaohongshu: "小红书",
    jingdong: "京东",
  };
  return labels[platform] || platform;
};

// 获取快递公司标签
const getExpressLabel = (express) => {
  const labels = {
    zhongtong: "中通",
    yunda: "韵达",
    shentong: "申通",
    yuantong: "圆通",
    youzheng: "邮政",
    jitu: "极兔",
    shunfeng: "顺丰",
    debang: "德邦",
  };
  return labels[express] || express;
};

// 获取交易记录列表
const fetchTransactions = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      search: searchForm?.search || "",
      paymentMethod: searchForm?.paymentMethod || "",
      payerId: searchForm?.payerId || "",
      payeeId: searchForm?.payeeId || "",
    };

    const response = await api.get("/transactions", { params });
    transactions.value = response.data.transactions;
    pagination.total = response.data.total;
  } catch (error) {
    ElMessage.error("获取交易记录失败");
  } finally {
    loading.value = false;
  }
};

let searchForm = null;

// 搜索
const handleSearch = (form) => {
  searchForm = form;
  pagination.page = 1;
  fetchTransactions();
};

// 重置搜索
const handleReset = (form) => {
  searchForm = form;
  pagination.page = 1;
  fetchTransactions();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchTransactions();
};

const handleCurrentChange = (page) => {
  pagination.page = page;
  fetchTransactions();
};

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (transaction) => {
  isEdit.value = true;
  currentTransaction.value = transaction;
  Object.assign(transactionForm, {
    ...transaction,
    relatedRecords: transaction.relatedRecords || [],
  });
  dialogVisible.value = true;
};

// 显示详情对话框
const showDetailDialog = (transaction) => {
  currentTransaction.value = transaction;
  detailDialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(transactionForm, {
    payerId: "",
    payeeId: "",
    transactionTime: "",
    amount: 0,
    paymentMethod: "",
    confirmTime: "",
    serialNumber: "",
    relatedRecords: [],
  });
  transactionFormRef.value?.resetFields();
  transactionFormRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!transactionFormRef.value) return;

  try {
    const valid = await transactionFormRef.value.validate();
    if (!valid) return;
  } catch {
    return;
  }

  submitLoading.value = true;

  try {
    if (isEdit.value) {
      await api.put(
        `/transactions/${currentTransaction.value._id}`,
        transactionForm
      );
      ElMessage.success("交易记录更新成功");
    } else {
      await api.post("/transactions", transactionForm);
      ElMessage.success("交易记录创建成功");
    }

    dialogVisible.value = false;
    fetchTransactions();
  } catch (error) {
    ElMessage.error(error.response?.data?.error || "操作失败");
  } finally {
    submitLoading.value = false;
  }
};

// 删除交易记录
const handleDelete = async (transaction) => {
  try {
    await ElMessageBox.confirm(`确定要删除这条交易记录吗？`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await api.delete(`/transactions/${transaction._id}`);
    ElMessage.success("交易记录删除成功");
    fetchTransactions();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchAllEntities();
  fetchAvailableRechargeRecords();
  fetchTransactions();
});
</script>

<style lang="scss" scoped>
.transaction-records {
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: $text-primary;
      font-size: 20px;
      font-weight: 600;
    }
  }

  .amount-text {
    font-weight: 600;
    color: $success-color;
  }

  .related-tag {
    margin-right: 4px;
    margin-bottom: 4px;
    font-size: 11px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .transaction-records {
    .page-header {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
    }
  }
}
</style>
